let Content = React.createClass({
    render:function(){
        return(
            <ScreenManagement />
        )
    }
});

//虚拟数据
let Data1=[{
        screenName:"屏幕2",
        imgUrl:"##",
        IP:"127.0.0.1",
        createTime:"2017/04/17",
        repeat:"不重复",
        id:1
    },
    {
        screenName:"屏幕3",
        imgUrl:"##",
        IP:"127.0.0.2",
        createTime:"2017/04/17",
        repeat:"不重复",
        id:2
    }],
    Data2=[{
        screenName:"屏幕4",
        imgUrl:"##",
        IP:"127.0.0.1",
        createTime:"2017/04/17",
        repeat:"不重复",
        id:1
    },
    {
        screenName:"屏幕5",
        imgUrl:"##",
        IP:"127.0.0.2",
        createTime:"2017/04/17",
        repeat:"不重复",
        id:2
    }],
    Data3=[{
        screenName:"屏幕6",
        imgUrl:"##",
        IP:"127.0.0.1",
        createTime:"2017/04/17",
        repeat:"不重复",
        id:1
    },
    {
        screenName:"屏幕7",
        imgUrl:"##",
        IP:"127.0.0.2",
        createTime:"2017/04/17",
        repeat:"不重复",
        id:2
    }],
    Data4=[{
        screenName:"屏幕8",
        imgUrl:"##",
        IP:"127.0.0.1",
        createTime:"2017/04/17",
        repeat:"不重复",
        id:1
    },
    {
        screenName:"屏幕9",
        imgUrl:"##",
        IP:"127.0.0.2",
        createTime:"2017/04/17",
        repeat:"不重复",
        id:2
    }],
    Data5=[{
        screenName:"屏幕10",
        imgUrl:"##",
        IP:"127.0.0.1",
        createTime:"2017/04/17",
        repeat:"不重复",
        id:1
    },
    {
        screenName:"屏幕11",
        imgUrl:"##",
        IP:"127.0.0.2",
        createTime:"2017/04/17",
        repeat:"不重复",
        id:2
    }];
//排序选项
const options = [
    { text: '名字', value: 1 },
    { text: 'IP地址', value: 2 },
    { text: '创建时间', value: 3 },
    { text: '操作', value: 4 },
];
//总组件
class ScreenManagement extends React.Component{
    constructor(){
        super();
        let todosArr = Data1.map(function(item,index){
            return {data:item,isDown:false,pause:true}
        })
        this.state={
            todos:todosArr,
            isAllChecked:false,
            totalPage:4,
            currentPage:1,
        }
    }
    //删除单条信息
    deleteInfo(index){
        this.state.todos.splice(index,1);
        this.setState({
            todos:this.state.todos
        })
    }
    //暂停
    togglePause(index){
        this.state.todos[index].pause=!this.state.todos[index].pause;
        this.setState({
            todos:this.state.todos
        })
    }

    //更改勾选框状态
    changeStatus(index,isDown){
        this.state.todos[index].isDown=isDown;
        this.setState({
            todos:this.state.todos
        })
        this.checkedAll();
    }
    //删除选中项
    deleteSelected(){
        let arr=this.state.todos.filter(function(todo){
            return !todo.isDown
        })
        this.setState({
            todos:arr
        })
        this.checkedAll();
    }
    //通过修改isAllChecked状态控制全选或者全不选
    changeAllStatus(isDown){
        this.state.todos.forEach(function(item){
            item.isDown=isDown
        })
        this.setState({
            todo:this.state.todos,
            isAllChecked:isDown
        })
        this.checkedAll();
    }
    //检查是否已经全选，然后修改全选框勾选状态
    checkedAll(){
        if(this.state.todos.every(function(item){ return item.isDown})){
            this.setState({
                isAllChecked:true
            })
        }else{
            this.setState({
                isAllChecked:false
            })
        }
    }
    checkedOne(){
        return this.state.todos.some(function(item){ return item.isDown});
    }
    changePageHandle(currentPage){
        let dataArr=[Data1,Data2,Data3,Data4,Data5];
        let curData = dataArr[currentPage-1];
        let todosArr = curData.map(function(item,index){
            return {data:item,isDown:false,pause:true}
        })
        this.setState({
            currentPage:currentPage,
            todos:todosArr
        }) 
    }
    render(){
        return(
            <div>
                <Table todos={this.state.todos}
                       deleteInfo={this.deleteInfo.bind(this)}
                       togglePause={this.togglePause.bind(this)}
                       changeStatus={this.changeStatus.bind(this)}
                       deleteSelected={this.deleteSelected.bind(this)}
                       isAllChecked={this.state.isAllChecked}
                       changeAllStatus={this.changeAllStatus.bind(this)}
                       checkedOne={this.checkedOne.bind(this)}
                       totalPage={this.state.totalPage}
                       currentPage={this.state.currentPage}
                       changePageHandle={this.changePageHandle.bind(this)}/>
            </div>
        )
    }
}
//数据展示及操作组件
class Table extends React.Component{
    handleDeleteSelected(){
        this.props.deleteSelected();
    }
    handleChangeAllStatus(e){
        this.props.changeAllStatus(e.target.checked);
    }
    render(){
        let that = this;
        return(
            <div className="col-xs-12">
                <div className="box box-primary">
                    <div className="box-header">
                        <h3 className="box-title">屏幕管理列表</h3>

                        <div className="box-tools">
                            <div className="input-group input-group-sm" style={{width: 150+'px'}}>
                                <input type="text" name="table_search" className="form-control pull-right" placeholder="搜索" />

                                <div className="input-group-btn">
                                    <button type="submit" className="btn btn-default"><i className="fa fa-search"></i></button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="box-header btnBar">
                        <div className="col-sm-1 no-padding">
                            <input type="checkbox" checked={this.props.isAllChecked} onChange={this.handleChangeAllStatus.bind(this)}/>
                        </div>
                        <button className={this.props.checkedOne()?"btn btn-default col-sm-2 fadeIn animated":"hidden"} onClick={this.handleDeleteSelected.bind(this)}>删除</button>
                    </div>
                <div className="box-body table-responsive no-padding">
                    <table className="table table-hover">
                        <tbody>
                                <tr>
                                    <th className="col-sm-1"></th>
                                    <th className="col-sm-3">
                                        <div className="row">
                                            <p className="col-sm-6">实时内容</p>
                                        </div>
                                    </th>
                                    <th className="col-sm-2">屏幕名称</th>
                                    <th className="col-sm-2">IP地址</th>
                                    <th className="col-sm-2">播放时间</th>
                                    <th className="col-sm-2 text-center">操作</th>
                                </tr>
                                {
                                    this.props.todos.map(function(item,index){
                                        return <Lists key={index} 
                                                    index={index} 
                                                    item={item} 
                                                    todo={that.props.todos[index]}
                                                    deleteInfo={that.props.deleteInfo.bind(that)}
                                                    changeStatus={that.props.changeStatus.bind(that)}
                                                    togglePause={that.props.togglePause.bind(that)}/>
                                    })
                                }
                        </tbody>
                    </table>
                    <Pagination totalPage={this.props.totalPage}
                                currentPage={this.props.currentPage}
                                changePageHandle={this.props.changePageHandle.bind(this)}/>
                </div>
            </div>
        </div>
        )
    }
}
//单个数据行组件
class Lists extends React.Component{
    handleDelete(){
        this.props.deleteInfo(this.props.index)
    }
    handlePause(){
        this.props.togglePause(this.props.index)
    }
    handleChangeStatus(e){
        this.props.changeStatus(this.props.index,e.target.checked)
    }
    render(){
        return(
            <tr>
                <td><input name="checkbox" type="checkbox" value="checkbox" checked={this.props.todo.isDown} onChange={this.handleChangeStatus.bind(this)}/></td>
                <td><img src="/dashboard/images/cai.jpg" alt="" className="row-second-img"/></td>
                <td><span>{this.props.item.data.screenName}</span>
                    </td>
                <td><span>{this.props.item.data.IP}</span></td>
                <td><span>{this.props.item.data.createTime}</span>
                    <p>{this.props.item.data.repeat}</p></td>
                <td>
                    {this.props.todo.pause?<div className="btn glyphicon glyphicon-pause" onClick={this.handlePause.bind(this)}>暂停</div>:<div className="btn glyphicon glyphicon-play" onClick={this.handlePause.bind(this)}>开始</div>}
                    <div className="btn glyphicon glyphicon-trash" onClick={this.props.deleteInfo}>删除</div></td>
            </tr>
        )
    }
}

//分页组件 Pagination
class Pagination extends React.Component {
	changePageHandle(currentPage){
		// 调用父组件的查询数据方法
		this.props.changePageHandle(currentPage);

	}
	render() {
		let pageHandle = this.changePageHandle.bind(this),
			currentPage = this.props.currentPage,
			totalPage = this.props.totalPage,
            arrList = [];
        for(let i=1;i<=totalPage;i++){
            if(i>5){
                arrList.push(<li><a href='#'>...</a></li>);
                break;
            }
            arrList.push(<li onClick={function(){currentPage=i;pageHandle(currentPage)}}><a href='#'>{i}</a></li>);
        }
		
		return (
            <div className="box-footer clearfix">
                <ul className="pagination pagination-sm no-margin pull-right">
                    <li onClick={(currentPage == 1)?'':function(){
                            currentPage = parseInt(currentPage) - 1;
                            pageHandle(currentPage);
                        }} 
                        className={(currentPage == 1)?'page-disable':''}>
                        <a href="#">«</a>
                    </li>
                    {arrList}
                    <li onClick={(currentPage == totalPage)?'':function(){
                            currentPage = parseInt(currentPage) + 1;
                            pageHandle(currentPage);
                        }} 
                        className={(currentPage == totalPage)?'page-disable':''}><a href="#">»</a></li>
                </ul>
            </div>
		);
	}

}
//点击下拉菜单组件开始
const { PropTypes } = React;
const propTypes = {
    width        : PropTypes.number,
    height       : PropTypes.number,
    chosen       : PropTypes.any,
    options      : PropTypes.array,
    tabIndex     : PropTypes.number,
    disabled     : PropTypes.bool,
    placeholder  : PropTypes.string,
    optionHeight : PropTypes.number
};

const defaultProps = {
    width        : 240,
    height       : 36,
    options      : [],
    tabIndex     : -1,
    disabled     : false,
    placeholder  : '',
    optionHeight : 30
};

class Relect extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            focused  : null,  // index of focused option
            showMenu : false  // whether show option
        };

        this.toggleMenu        = this.toggleMenu.bind(this);
        this.handleBlur        = this.handleBlur.bind(this);
        this.handleClear       = this.handleClear.bind(this);
        this.handleChoose      = this.handleChoose.bind(this);
        this.handleKeyDown     = this.handleKeyDown.bind(this);
        this.focusOption       = this.focusOption.bind(this);
        this.moveFocusedOption = this.moveFocusedOption.bind(this);
    }

    componentDidMount() {
        this.menuDOM = ReactDOM.findDOMNode(this.refs.menu);
    }

    toggleMenu() {
        this.setState({ showMenu: !this.state.showMenu });
    };

    handleChoose(index) {
        this.props.onChange(index);
        this.setState({ showMenu : false });
    };

    handleClear(e) {
        e.stopPropagation();
        this.setState({ showMenu : false });
        this.props.onChange(null);
    };

    handleBlur() {
        this.setState({ showMenu : false })
    };

    handleKeyDown(e) {
        switch (e.which) {
            case 8 : // Delete
                this.handleClear(e);
                break;
            case 27: // Esc
                this.setState({ showMenu : false });
                break;
            case 13: // Enter
            case 32: // Space
                if (this.state.showMenu && this.state.focused !== null) {
                    this.handleChoose(this.state.focused);
                } else {
                    this.toggleMenu();
                }
                break;
            case 38: // Up
                this.moveFocusedOption(-1);
                break;
            case 40: // Down
                this.moveFocusedOption(1);
                break;
            default:
                return;
        }
        e.preventDefault();
    };

    moveFocusedOption(move) {
        if (!this.state.showMenu) {
            this.setState({ showMenu : true });
            return;
        }
        let focused = this.state.focused;
        let length  = this.props.options.length;
        focused = focused === null ? 0 : (focused + move + length) % length;
        this.focusOption(focused);
    };

    focusOption(focused) {
        this.setState({ focused });

        // calc offset
        // displays up to 8 options in the same time
        let length = this.props.options.length;
        if (length > 8) {
            let height  = this.props.optionHeight;
            let current = this.menuDOM.scrollTop;
            let max = Math.min((length - 8) * height, focused * height);
            let min = Math.max(0, (focused - 7) * height);

            if (current > max) {
                this.menuDOM.scrollTop = max;
            } else if (current < min) {
                this.menuDOM.scrollTop = min;
            }
        }
    };

    render() {

        const props = this.props;
        const { showMenu, focused } = this.state;

        const style = {
            width      : props.width,
            lineHeight : props.height - 2 + 'px'
        };

        return (
            <div style={style}
                 className="relect"
                 tabIndex={props.tabIndex}
                 onBlur={this.handleBlur}
                 onKeyDown={this.handleKeyDown}
            >
                <Box {...props}
                     showMenu={showMenu}
                     onClick={this.toggleMenu}
                     handleClear={this.handleClear}
                />
                <Menu {...props}
                      ref="menu"
                      focused={focused}
                      showMenu={showMenu}
                      focusOption={this.focusOption}
                      handleChoose={this.handleChoose}
                />
            </div>
        )
    }
}

Relect.propTypes = propTypes;
Relect.defaultProps = defaultProps;

class Box extends React.Component {

    renderContent(props) {
        const { chosen, options, disabled } = props;
        if (typeof chosen === 'number' && options[chosen] !== undefined) {
            const clear = disabled ? null : <span className="relect-clear" onClick={props.handleClear} />;
            return <span>{options[chosen].text || options[chosen]}{clear}</span>;
        } else {
            return <span className="relect-placeholder">{props.placeholder}</span>
        }
    }

    render() {
        const props = this.props;
        const className = 'relect-box' + (props.disabled ? ' relect-box-disabled' : '');

        return (
            <div className={className} onClick={props.onClick} >
                {this.renderContent(props)}
                <span className="relect-arrow" />
            </div>
        )
    }
}

class Menu extends React.Component {

    render() {

        const props = this.props;
        const style = {
            top        : props.height - 1,
            display    : props.showMenu && !props.disabled ? '' : 'none',
            lineHeight : props.optionHeight + 'px',
            maxHeight  : props.optionHeight * 8 + 2
        };

        const options = props.options.map((item, index) => {
            const className = index === props.focused ? 'relect-focused-option' : '';
            return (
                <li key={index}
                    className={className}
                    onClick={props.handleChoose.bind(null, index)}
                    onMouseEnter={props.focusOption.bind(null, index)}
                >
                    {item.text || item}
                </li>
            )
        });

        return <ul className="relect-option thin-scroll" style={style}>{options}</ul>;
    }
}